import re

from django_redis import get_redis_connection
from rest_framework import serializers

#有模型使用Model，，，
from users.models import User, Address
from users.utils import generic_verify_url


class RegisterCreateUserSerializer(serializers.ModelSerializer):
    #username、mobile、password、password2、sms_code、allow
    #仅仅在注册时有效，输入时有效，序列化时无效
    password2 = serializers.CharField(label="确认密码",required=True,write_only=True)
    sms_code = serializers.CharField(label="图片验证码",max_length=6,min_length=6,required=True,write_only=True)
    allow = serializers.CharField(label="同意登陆协议",required=True,write_only=True)

    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ['id','username','mobile','password','password2','sms_code','allow','token']

        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    #单个字段校验  是否同意协议、手机号

    def validate_mobile(self,value):
        if not re.match(r'1[345789]\d{9}', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value
    def validate_allow(self,value):
        # 注意,前段提交的是否同意,我们已经转换为字符串
        if value != 'true':
            raise serializers.ValidationError('您未同意协议')
        return value
        # 多个字段校验   密码确认密码、图片验证码
    def validate(self,attrs):
        #比较密码
        password = attrs['password']
        # password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError("密码不一致")
        # 比较手机验证码
        # 获取用户提交的验证码
        code = attrs.get('sms_code')
        # 获取redis中的验证码
        redis_conn = get_redis_connection('code')
        # 获取手机号码
        mobile = attrs.get('mobile')
        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code is None:
            raise serializers.ValidationError('验证码过期')

        if redis_code.decode() != code:
            raise serializers.ValidationError('验证码不正确')

        return attrs
    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()

        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user

#用户个人中心序列化器
class UserCenterINfoSerializer(serializers.ModelSerializer):
    class Meta:
        model= User
        fields = ('id','username','mobile','email','email_active')


#用户邮箱序列化器
class UserUpdateEmailSrializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email',)

    #保存数据save调用update方法,之后在发送邮件,即重写update方法
    def update(self, instance, validated_data):
        email = validated_data.get('email')
        instance.email = email
        instance.save()

        #发送激活文件

        # from django.core.mail import send_mail
        # # subject, message, from_email, recipient_list,
        # # subject,   主题
        # subject = '美多商城激活邮件'
        # # message, 内容
        # message = '嘎嘎嘎'
        # # from_email,  发件人
        # from_email = '美多商城<18234153757@163.com>'
        # # recipient_list, 收件人列表
        # recipient_list = [email]
        #
        # # 我们要生成一个 激活的url
        # # http://ip:port/succes.html?token=xxxx
        # # token 应该包含 用户的信息
        # verify_url = generic_verify_url(instance.id,email)
        #
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        #
        # send_mail(
        #     subject=subject,
        #     message=message,
        #     from_email=from_email,
        #     recipient_list=recipient_list,
        #     html_message=html_message)

        # #发送短信是耗时操作,使用异步
        from celery_tasks.email.tasks import send_verify_email
        #
        send_verify_email.delay(instance.id,email)
        return instance








#展示所有列表序列化器
# class ListAddressSerializer(serializers.ModelSerializer):
#     province = serializers.StringRelatedField(read_only=True)
#     city = serializers.StringRelatedField(read_only=True)
#     district = serializers.StringRelatedField(read_only=True)
#     province_id = serializers.IntegerField(label='省ID', required=True)
#     city_id = serializers.IntegerField(label='市ID', required=True)
#     district_id = serializers.IntegerField(label='区ID', required=True)
#     mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
#
#     class Meta:
#         model = Address
#         exclude = ('user', 'is_deleted', 'create_time', 'update_time')


#新增地址序列化器
class AddressSerialize(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted','create_time', 'update_time')

    def create(self, validated_data):
        # Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

#删除地址的序列化器











